home *** CD-ROM | disk | FTP | other *** search
/ MacFormat España 4 / MacFormat n. 4 (Spain) / MacFormat 4.bin / La ciudad del ShareWare / Desarrollo / macgzip_03b2-src / deflate.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-11-08  |  28.5 KB  |  763 lines

  1. /* deflate.c -- compress data using the deflation algorithm
  2.  * Copyright (C) 1992-1993 Jean-loup Gailly
  3.  * This is free software; you can redistribute it and/or modify it under the
  4.  * terms of the GNU General Public License, see the file COPYING.
  5.  */
  6.  
  7. /*
  8.  * Modified:1993 by SPDsoft for MacGzip
  9.  *
  10.  */
  11.  
  12. /*
  13.  *  PURPOSE
  14.  *
  15.  *      Identify new text as repetitions of old text within a fixed-
  16.  *      length sliding window trailing behind the new text.
  17.  *
  18.  *  DISCUSSION
  19.  *
  20.  *      The "deflation" process depends on being able to identify portions
  21.  *      of the input text which are identical to earlier input (within a
  22.  *      sliding window trailing behind the input currently being processed).
  23.  *
  24.  *      The most straightforward technique turns out to be the fastest for
  25.  *      most input files: try all possible matches and select the longest.
  26.  *      The key feature of this algorithm is that insertions into the string
  27.  *      dictionary are very simple and thus fast, and deletions are avoided
  28.  *      completely. Insertions are performed at each input character, whereas
  29.  *      string matches are performed only when the previous match ends. So it
  30.  *      is preferable to spend more time in matches to allow very fast string
  31.  *      insertions and avoid deletions. The matching algorithm for small
  32.  *      strings is inspired from that of Rabin & Karp. A brute force approach
  33.  *      is used to find longer strings when a small match has been found.
  34.  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  35.  *      (by Leonid Broukhis).
  36.  *         A previous version of this file used a more sophisticated algorithm
  37.  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
  38.  *      time, but has a larger average cost, uses more memory and is patented.
  39.  *      However the F&G algorithm may be faster for some highly redundant
  40.  *      files if the parameter max_chain_length (described below) is too large.
  41.  *
  42.  *  ACKNOWLEDGEMENTS
  43.  *
  44.  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  45.  *      I found it in 'freeze' written by Leonid Broukhis.
  46.  *      Thanks to many info-zippers for bug reports and testing.
  47.  *
  48.  *  REFERENCES
  49.  *
  50.  *      APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
  51.  *
  52.  *      A description of the Rabin and Karp algorithm is given in the book
  53.  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  54.  *
  55.  *      Fiala,E.R., and Greene,D.H.
  56.  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  57.  *
  58.  *  INTERFACE
  59.  *
  60.  *      void lm_init (int pack_level, ush *flags)
  61.  *          Initialize the "longest match" routines for a new file
  62.  *
  63.  *      ulg deflate (void)
  64.  *          Processes a new input file and return its compressed length. Sets
  65.  *          the compressed length, crc, deflate flags and internal file
  66.  *          attributes.
  67.  */
  68.  
  69. #include <stdio.h>
  70.  
  71. #include "tailor.h"
  72. #include "gzip.h"
  73. #include "lzw.h" /* just for consistency checking */
  74.  
  75. #ifdef RCSID
  76. static char rcsid[] = "$Id: deflate.c,v 0.15 1993/06/24 10:53:53 jloup Exp $";
  77. #endif
  78.  
  79. /* ===========================================================================
  80.  * Configuration parameters
  81.  */
  82.  
  83. /* Compile with MEDIUM_MEM to reduce the memory requirements or
  84.  * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
  85.  * entire input file can be held in memory (not possible on 16 bit systems).
  86.  * Warning: defining these symbols affects HASH_BITS (see below) and thus
  87.  * affects the compression ratio. The compressed output
  88.  * is still correct, and might even be smaller in some cases.
  89.  */
  90.  
  91. #ifdef SMALL_MEM
  92. #   define HASH_BITS  13  /* Number of bits used to hash strings */
  93. #endif
  94. #ifdef MEDIUM_MEM
  95. #   define HASH_BITS  14
  96. #endif
  97. #ifndef HASH_BITS
  98. #   define HASH_BITS  15
  99.    /* For portability to 16 bit machines, do not use values above 15. */
  100. #endif
  101.  
  102. /* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
  103.  * window with tab_suffix. Check that we can do this:
  104.  */
  105. #if (WSIZE<<1) > (1<<BITS)
  106.    error: cannot overlay window with tab_suffix and prev with tab_prefix0
  107. #endif
  108. #if HASH_BITS > BITS-1
  109.    error: cannot overlay head with tab_prefix1
  110. #endif
  111.  
  112. #define HASH_SIZE (unsigned)(1<<HASH_BITS)
  113. #define HASH_MASK (HASH_SIZE-1)
  114. #define WMASK     (WSIZE-1)
  115. /* HASH_SIZE and WSIZE must be powers of two */
  116.  
  117. #define NIL 0
  118. /* Tail of hash chains */
  119.  
  120. #define FAST 4
  121. #define SLOW 2
  122. /* speed options for the general purpose bit flag */
  123.  
  124. #ifndef TOO_FAR
  125. #  define TOO_FAR 4096
  126. #endif
  127. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  128.  
  129. /* ===========================================================================
  130.  * Local data used by the "longest match" routines.
  131.  */
  132.  
  133. typedef ush Pos;
  134. typedef unsigned IPos;
  135. /* A Pos is an index in the character window. We use short instead of int to
  136.  * save space in the various tables. IPos is used only for parameter passing.
  137.  */
  138.  
  139. /* DECLARE(uch, window, 2L*WSIZE); */
  140. /* Sliding window. Input bytes are read into the second half of the window,
  141.  * and move to the first half later to keep a dictionary of at least WSIZE
  142.  * bytes. With this organization, matches are limited to a distance of
  143.  * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
  144.  * performed with a length multiple of the block size. Also, it limits
  145.  * the window size to 64K, which is quite useful on MSDOS.
  146.  * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
  147.  * be less efficient).
  148.  */
  149.  
  150. /* DECLARE(Pos, prev, WSIZE); */
  151. /* Link to older string with same hash index. To limit the size of this
  152.  * array to 64K, this link is maintained only for the last 32K strings.
  153.  * An index in this array is thus a window index modulo 32K.
  154.  */
  155.  
  156. /* DECLARE(Pos, head, 1<<HASH_BITS); */
  157. /* Heads of the hash chains or NIL. */
  158.  
  159. ulg window_size = (ulg)2*WSIZE;
  160. /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
  161.  * input file length plus MIN_LOOKAHEAD.
  162.  */
  163.  
  164. long block_start;
  165. /* window position at the beginning of the current output block. Gets
  166.  * negative when the window is moved backwards.
  167.  */
  168.  
  169. local unsigned ins_h;  /* hash index of string to be inserted */
  170.  
  171. #define H_SHIFT  ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
  172. /* Number of bits by which ins_h and del_h must be shifted at each
  173.  * input step. It must be such that after MIN_MATCH steps, the oldest
  174.  * byte no longer takes part in the hash key, that is:
  175.  *   H_SHIFT * MIN_MATCH >= HASH_BITS
  176.  */
  177.  
  178. unsigned int near prev_length;
  179. /* Length of the best match at previous step. Matches not greater than this
  180.  * are discarded. This is used in the lazy match evaluation.
  181.  */
  182.  
  183.       unsigned near strstart;      /* start of string to insert */
  184.       unsigned near match_start;   /* start of matching string */
  185. local int           eofile;        /* flag set at end of input file */
  186. local unsigned      lookahead;     /* number of valid bytes ahead in window */
  187.  
  188. unsigned near max_chain_length;
  189. /* To speed up deflation, hash chains are never searched beyond this length.
  190.  * A higher limit improves compression ratio but degrades the speed.
  191.  */
  192.  
  193. local unsigned int max_lazy_match;
  194. /* Attempt to find a better match only when the current match is strictly
  195.  * smaller than this value. This mechanism is used only for compression
  196.  * levels >= 4.
  197.  */
  198. #define max_insert_length  max_lazy_match
  199. /* Insert new strings in the hash table only if the match length
  200.  * is not greater than this length. This saves time but degrades compression.
  201.  * max_insert_length is used only for compression levels <= 3.
  202.  */
  203.  
  204. local int compr_level;
  205. /* compression level (1..9) */
  206.  
  207. unsigned near good_match;
  208. /* Use a faster search when the previous match is longer than this */
  209.  
  210.  
  211. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  212.  * the desired pack level (0..9). The values given below have been tuned to
  213.  * exclude worst case performance for pathological files. Better values may be
  214.  * found for specific files.
  215.  */
  216.  
  217. typedef struct config {
  218.    ush good_length; /* reduce lazy search above this match length */
  219.    ush max_lazy;    /* do not perform lazy search above this match length */
  220.    ush nice_length; /* quit search above this match length */
  221.    ush max_chain;
  222. } config;
  223.  
  224. #ifdef  FULL_SEARCH
  225. # define nice_match MAX_MATCH
  226. #else
  227.   int near nice_match; /* Stop searching when current match exceeds this */
  228. #endif
  229.  
  230. local config configuration_table[10] = {
  231. /*      good lazy nice chain */
  232. /* 0 */ {0,    0,  0,    0},  /* store only */
  233. /* 1 */ {4,    4,  8,    4},  /* maximum speed, no lazy matches */
  234. /* 2 */ {4,    5, 16,    8},
  235. /* 3 */ {4,    6, 32,   32},
  236.  
  237. /* 4 */ {4,    4, 16,   16},  /* lazy matches */
  238. /* 5 */ {8,   16, 32,   32},
  239. /* 6 */ {8,   16, 128, 128},
  240. /* 7 */ {8,   32, 128, 256},
  241. /* 8 */ {32, 128, 258, 1024},
  242. /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
  243.  
  244. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  245.  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  246.  * meaning.
  247.  */
  248.  
  249. #define EQUAL 0
  250. /* result of memcmp for equal strings */
  251.  
  252. /* ===========================================================================
  253.  *  Prototypes for local functions.
  254.  */
  255. local void fill_window   OF((void));
  256. local ulg deflate_fast   OF((void));
  257.  
  258.       int  longest_match OF((IPos cur_match));
  259. #ifdef ASMV
  260.       void match_init OF((void)); /* asm code initialization */
  261. #endif
  262.  
  263. #ifdef DEBUG
  264. local  void check_match OF((IPos start, IPos match, int length));
  265. #endif
  266.  
  267. /* ===========================================================================
  268.  * Update a hash value with the given input byte
  269.  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
  270.  *    input characters, so that a running hash key can be computed from the
  271.  *    previous key instead of complete recalculation each time.
  272.  */
  273. #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
  274.  
  275. /* ===========================================================================
  276.  * Insert string s in the dictionary and set match_head to the previous head
  277.  * of the hash chain (the most recent string with same hash key). Return
  278.  * the previous length of the hash chain.
  279.  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
  280.  *    input characters and the first MIN_MATCH bytes of s are valid
  281.  *    (except for the last MIN_MATCH-1 bytes of the input file).
  282.  */
  283. #define INSERT_STRING(s, match_head) \
  284.    (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
  285.     prev[(s) & WMASK] = match_head = head[ins_h], \
  286.     head[ins_h] = (s))
  287.  
  288. /* ===========================================================================
  289.  * Initialize the "longest match" routines for a new file
  290.  */
  291. void lm_init (pack_level, flags)
  292.     int pack_level; /* 0: store, 1: best speed, 9: best compression */
  293.     ush *flags;     /* general purpose bit flag */
  294. {
  295.     register unsigned j;
  296.  
  297.     if (pack_level < 1 || pack_level > 9) error("bad pack level");
  298.     compr_level = pack_level;
  299.  
  300.     /* Initialize the hash table. */
  301. #if defined(MAXSEG_64K) && HASH_BITS == 15
  302.     for (j = 0;  j < HASH_SIZE; j++) head[j] = NIL;
  303. #else
  304.     memzero((char*)head, HASH_SIZE*sizeof(*head));
  305. #endif
  306.     /* prev will be initialized on the fly */
  307.  
  308.     /* Set the default configuration parameters:
  309.      */
  310.     max_lazy_match   = configuration_table[pack_level].max_lazy;
  311.     good_match       = configuration_table[pack_level].good_length;
  312. #ifndef FULL_SEARCH
  313.     nice_match       = configuration_table[pack_level].nice_length;
  314. #endif
  315.     max_chain_length = configuration_table[pack_level].max_chain;
  316.     if (pack_level == 1) {
  317.        *flags |= FAST;
  318.     } else if (pack_level == 9) {
  319.        *flags |= SLOW;
  320.     }
  321.     /* ??? reduce max_chain_length for binary files */
  322.  
  323.     strstart = 0;
  324.     block_start = 0L;
  325. #ifdef ASMV
  326.     match_init(); /* initialize the asm code */
  327. #endif
  328.  
  329.     lookahead = read_buf((char*)window,
  330.              sizeof(int) <= 2 ? (unsigned)WSIZE : 2*WSIZE);
  331.  
  332.     if (lookahead == 0 || lookahead == (unsigned)EOF) {
  333.        eofile = 1, lookahead = 0;
  334.        return;
  335.     }
  336.     eofile = 0;
  337.     /* Make sure that we always have enough lookahead. This is important
  338.      * if input comes from a device such as a tty.
  339.      */
  340.     while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  341.  
  342.     ins_h = 0;
  343.     for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(ins_h, window[j]);
  344.     /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  345.      * not important since only literal bytes will be emitted.
  346.      */
  347. }
  348.  
  349. /* ===========================================================================
  350.  * Set match_start to the longest match starting at the given string and
  351.  * return its length. Matches shorter or equal to prev_length are discarded,
  352.  * in which case the result is equal to prev_length and match_start is
  353.  * garbage.
  354.  * IN assertions: cur_match is the head of the hash chain for the current
  355.  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  356.  */
  357. #ifndef ASMV
  358. /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
  359.  * match.s. The code is functionally equivalent, so you can use the C version
  360.  * if desired.
  361.  */
  362. int longest_match(cur_match)
  363.     IPos cur_match;                             /* current match */
  364. {
  365.     unsigned chain_length = max_chain_length;   /* max hash chain length */
  366.     register uch *scan = window + strstart;     /* current string */
  367.     register uch *match;                        /* matched string */
  368.     register int len;                           /* length of current match */
  369.     int best_len = prev_length;                 /* best match length so far */
  370.     IPos limit = strstart > (IPos)MAX_DIST ? strstart - (IPos)MAX_DIST : NIL;
  371.     /* Stop when cur_match becomes <= limit. To simplify the code,
  372.      * we prevent matches with the string of window index 0.
  373.      */
  374.  
  375. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  376.  * It is easy to get rid of this optimization if necessary.
  377.  */
  378. #if HASH_BITS < 8 || MAX_MATCH != 258
  379.    error: Code too clever
  380. #endif
  381.  
  382. #ifdef UNALIGNED_OK
  383.     /* Compare two bytes at a time. Note: this is not always beneficial.
  384.      * Try with and without -DUNALIGNED_OK to check.
  385.      */
  386.     register uch *strend = window + strstart + MAX_MATCH - 1;
  387.     register ush scan_start = *(ush*)scan;
  388.     register ush scan_end   = *(ush*)(scan+best_len-1);
  389. #else
  390.     register uch *strend = window + strstart + MAX_MATCH;
  391.     register uch scan_end1  = scan[best_len-1];
  392.     register uch scan_end   = scan[best_len];
  393. #endif
  394.  
  395.     /* Do not waste too much time if we already have a good match: */
  396.     if (prev_length >= good_match) {
  397.         chain_length >>= 2;
  398.     }
  399.     Assert(strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
  400.  
  401.     do {
  402.         Assert(cur_match < strstart, "no future");
  403.         match = window + cur_match;
  404.  
  405.         /* Skip to next match if the match length cannot increase
  406.          * or if the match length is less than 2:
  407.          */
  408. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  409.         /* This code assumes sizeof(unsigned short) == 2. Do not use
  410.          * UNALIGNED_OK if your compiler uses a different size.
  411.          */
  412.         if (*(ush*)(match+best_len-1) != scan_end ||
  413.             *(ush*)match != scan_start) continue;
  414.  
  415.         /* It is not necessary to compare scan[2] and match[2] since they are
  416.          * always equal when the other bytes match, given that the hash keys
  417.          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  418.          * strstart+3, +5, ... up to strstart+257. We check for insufficient
  419.          * lookahead only every 4th comparison; the 128th check will be made
  420.          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  421.          * necessary to put more guard bytes at the end of the window, or
  422.          * to check more often for insufficient lookahead.
  423.          */
  424.         scan++, match++;
  425.         do {
  426.         } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
  427.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  428.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  429.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  430.                  scan < strend);
  431.         /* The funny "do {}" generates better code on most compilers */
  432.  
  433.         /* Here, scan <= window+strstart+257 */
  434.         Assert(scan <= window+(unsigned)(window_size-1), "wild scan");
  435.         if (*scan == *match) scan++;
  436.  
  437.         len = (MAX_MATCH - 1) - (int)(strend-scan);
  438.         scan = strend - (MAX_MATCH-1);
  439.  
  440. #else /* UNALIGNED_OK */
  441.  
  442.         if (match[best_len]   != scan_end  ||
  443.             match[best_len-1] != scan_end1 ||
  444.             *match            != *scan     ||
  445.             *++match          != scan[1])      continue;
  446.  
  447.         /* The check at best_len-1 can be removed because it will be made
  448.          * again later. (This heuristic is not always a win.)
  449.          * It is not necessary to compare scan[2] and match[2] since they
  450.          * are always equal when the other bytes match, given that
  451.          * the hash keys are equal and that HASH_BITS >= 8.
  452.          */
  453.         scan += 2, match++;
  454.  
  455.         /* We check for insufficient lookahead only every 8th comparison;
  456.          * the 256th check will be made at strstart+258.
  457.          */
  458.         do {
  459.         } while (*++scan == *++match && *++scan == *++match &&
  460.                  *++scan == *++match && *++scan == *++match &&
  461.                  *++scan == *++match && *++scan == *++match &&
  462.                  *++scan == *++match && *++scan == *++match &&
  463.                  scan < strend);
  464.  
  465.         len = MAX_MATCH - (int)(strend - scan);
  466.         scan = strend - MAX_MATCH;
  467.  
  468. #endif /* UNALIGNED_OK */
  469.  
  470.         if (len > best_len) {
  471.             match_start = cur_match;
  472.             best_len = len;
  473.             if (len >= nice_match) break;
  474. #ifdef UNALIGNED_OK
  475.             scan_end = *(ush*)(scan+best_len-1);
  476. #else
  477.             scan_end1  = scan[best_len-1];
  478.             scan_end   = scan[best_len];
  479. #endif
  480.         }
  481.     } while ((cur_match = prev[cur_match & WMASK]) > limit
  482.          && --chain_length != 0);
  483.  
  484.     return best_len;
  485. }
  486. #endif /* ASMV */
  487.  
  488. #ifdef DEBUG
  489. /* ===========================================================================
  490.  * Check that the match at match_start is indeed a match.
  491.  */
  492. local void check_match(start, match, length)
  493.     IPos start, match;
  494.     int length;
  495. {
  496.     /* check that the match is indeed a match */
  497.     if (memcmp((char*)window + match,
  498.                 (char*)window + start, length) != EQUAL) {
  499.         sprintf(strerr,
  500.             " start %d, match %d, length %d; invalid match",
  501.             start, match, length);
  502.         error(strerr);
  503.     }
  504.     if (verbose > 1) {
  505.         fprintf(stderr,"\\[%d,%d]", start-match, length);
  506.         do { putc(window[start++], stderr); } while (--length != 0);
  507.     }
  508. }
  509. #else
  510. #  define check_match(start, match, length)
  511. #endif
  512.  
  513. /* ===========================================================================
  514.  * Fill the window when the lookahead becomes insufficient.
  515.  * Updates strstart and lookahead, and sets eofile if end of input file.
  516.  * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
  517.  * OUT assertions: at least one byte has been read, or eofile is set;
  518.  *    file reads are performed for at least two bytes (required for the
  519.  *    translate_eol option).
  520.  */
  521. local void fill_window()
  522. {
  523.     register unsigned n, m;
  524.     unsigned more = (unsigned)(window_size - (ulg)lookahead - (ulg)strstart);
  525.     /* Amount of free space at the end of the window. */
  526.  
  527.     /* If the window is almost full and there is insufficient lookahead,
  528.      * move the upper half to the lower one to make room in the upper half.
  529.      */
  530.     if (more == (unsigned)EOF) {
  531.         /* Very unlikely, but possible on 16 bit machine if strstart == 0
  532.          * and lookahead == 1 (input done one byte at time)
  533.          */
  534.         more--;
  535.     } else if (strstart >= WSIZE+MAX_DIST) {
  536.         /* By the IN assertion, the window is not empty so we can't confuse
  537.          * more == 0 with more == 64K on a 16 bit machine.
  538.          */
  539.         Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM");
  540.  
  541.         memcpy((char*)window, (char*)window+WSIZE, (unsigned)WSIZE);
  542.         match_start -= WSIZE;
  543.         strstart    -= WSIZE; /* we now have strstart >= MAX_DIST: */
  544.  
  545.         block_start -= (long) WSIZE;
  546.  
  547.         for (n = 0; n < HASH_SIZE; n++) {
  548.             m = head[n];
  549.             head[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  550.         }
  551.         for (n = 0; n < WSIZE; n++) {
  552.             m = prev[n];
  553.      nse.
  554.  
  555. @item
  556. If the distribution and/or use of the Program is restricted in
  557. certain countries either by patents or by copyrighted interfaces, the
  558. original copyright holder who places the Program under this License
  559. may add an explicit geographical distribution limitation excluding
  560. those countries, so that distribution is permitted only in or among
  561. countries not thus excluded.  In such case, this License incorporates
  562. the limitation as if written in the body of this License.
  563.  
  564. @item
  565. The Free Software Foundation may publish revised and/or new versions
  566. of the General Public License from time to time.  Such new versions will
  567. be similar in spirit to the present version, but may differ in detail to
  568. address new problems or concerns.
  569.  
  570. Each version is given a distinguishing version number.  If the Program
  571. specifies a version number of this License which applies to it and ``any
  572. later version'', you have the option of following the terms and conditions
  573. either of that version or of any later version published by the Free
  574. Software Foundation.  If the Program does not specify a version number of
  575. this License, you may choose any version ever published by the Free Software
  576. Foundation.
  577.  
  578. @item
  579. If you wish to incorporate parts of the Program into other free
  580. programs whose distribution conditions are different, write to the author
  581. to ask for permission.  For software which is copyrighted by the Free
  582. Software Foundation, write to the Free Software Foundation; we sometimes
  583. make exceptions for this.  Our decision will be guided by the two goals
  584. of preserving the free status of all derivatives of our free software and
  585. of promoting the sharing and reuse of software generally.
  586.  
  587. @iftex
  588. @heading NO WARRANTY
  589. @end iftex
  590. @ifinfo
  591. @center NO WARRANTY
  592. @end ifinfo
  593.  
  594. @item
  595. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  596. FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  597. OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  598. PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPREtself at the start of the input file).
  599.              */
  600.             match_length = longest_match (hash_head);
  601.             /* longest_match() sets match_start */
  602.             if (match_length > lookahead) match_length = lookahead;
  603.         }
  604.         if (match_length >= MIN_MATCH) {
  605.             check_match(strstart, match_start, match_length);
  606.  
  607.             flush = ct_tally(strstart-match_start, match_length - MIN_MATCH);
  608.  
  609.             lookahead -= match_length;
  610.  
  611.         /* Insert new strings in the hash table only if the match length
  612.              * is not too large. This saves time but degrades compression.
  613.              */
  614.             if (match_length <= max_insert_length) {
  615.                 match_length--; /* string at strstart already in hash table */
  616.                 do {
  617.                     strstart++;
  618.                     INSERT_STRING(strstart, hash_head);
  619.                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  620.                      * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  621.                      * these bytes are garbage, but it does not matter since
  622.                      * the next lookahead bytes will be emitted as literals.
  623.                      */
  624.                 } while (--match_length != 0);
  625.             strstart++; 
  626.             } else {
  627.             strstart += match_length;
  628.             match_length = 0;
  629.             ins_h = window[strstart];
  630.             UPDATE_HASH(ins_h, window[strstart+1]);
  631. #if MIN_MATCH != 3
  632.                 Call UPDATE_HASH() MIN_MATCH-3 more times
  633. #endif
  634.             }
  635.         } else {
  636.             /* No match, output a literal byte */
  637.             Tracevv((stderr,"%c",window[strstart]));
  638.             flush = ct_tally (0, window[strstart]);
  639.             lookahead--;
  640.         strstart++; 
  641.         }
  642.         if (flush) FLUSH_BLOCK(0), block_start = strstart;
  643.  
  644.         /* Make sure that we always have enough lookahead, except
  645.          * at the end of the input file. We need MAX_MATCH bytes
  646.          * for the next match, plus MIN_MATCH bytes to insert the
  647.          * string following the next match.
  648.          */
  649.         while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  650.  
  651.     }
  652.     return FLUSH_BLOCK(1); /* eof */
  653. }
  654.  
  655. /* ===========================================================================
  656.  * Same as above, but achieves better compression. We use a lazy
  657.  * evaluation for matches: a match is finally adopted only if there is
  658.  * no better match at the next window position.
  659.  */
  660. ulg deflate()
  661. {
  662.     IPos hash_head;          /* head of hash chain */
  663.     IPos prev_match;         /* previous match */
  664.     int flush;               /* set if current block must be flushed */
  665.     int match_available = 0; /* set if previous match exists */
  666.     register unsigned match_length = MIN_MATCH-1; /* length of best match */
  667. #ifdef DEBUG
  668.     extern long isize;        /* byte length of input file, for debug only */
  669. #endif
  670.  
  671.     if (compr_level <= 3) return deflate_fast(); /* optimized for speed */
  672.  
  673.     /* Process the input block. */
  674.     while (lookahead != 0) {
  675.         /* Insert the string window[strstart .. strstart+2] in the
  676.          * dictionary, and set hash_head to the head of the hash chain:
  677.          */
  678.         INSERT_STRING(strstart, hash_head);
  679.  
  680.         /* Find the longest match, discarding those <= prev_length.
  681.          */
  682.         prev_length = match_length, prev_match = match_start;
  683.         match_length = MIN_MATCH-1;
  684.  
  685.         if (hash_head != NIL && prev_length < max_lazy_match &&
  686.             strstart - hash_head <= MAX_DIST) {
  687.             /* To simplify the code, we prevent matches with the string
  688.              * of window index 0 (in particular we have to avoid a match
  689.              * of the string with itself at the start of the input file).
  690.              */
  691.             match_length = longest_match (hash_head);
  692.             /* longest_match() sets match_start */
  693.             if (match_length > lookahead) match_length = lookahead;
  694.  
  695.             /* Ignore a length 3 match if it is too distant: */
  696.             if (match_length == MIN_MATCH && strstart-match_start > TOO_FAR){
  697.                 /* If prev_match is also MIN_MATCH, match_start is garbage
  698.                  * but we will ignore the current match anyway.
  699.                  */
  700.                 match_length--;
  701.             }
  702.         }
  703.         /* If there was a match at the previous step and the current
  704.          * match is not better, output the previous match:
  705.          */
  706.         if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  707.  
  708.             check_match(strstart-1, prev_match, prev_length);
  709.  
  710.             flush = ct_tally(strstart-1-prev_match, prev_length - MIN_MATCH);
  711.  
  712.             /* Insert in hash table all strings up to the end of the match.
  713.              * strstart-1 and strstart are already inserted.
  714.              */
  715.             lookahead -= prev_length-1;
  716.             prev_length -= 2;
  717.             do {
  718.                 strstart++;
  719.                 INSERT_STRING(strstart, hash_head);
  720.                 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  721.                  * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  722.                  * these bytes are garbage, but it does not matter since the
  723.                  * next lookahead bytes will always be emitted as literals.
  724.                  */
  725.             } while (--prev_length != 0);
  726.             match_available = 0;
  727.             match_length = MIN_MATCH-1;
  728.             strstart++;
  729.             if (flush) FLUSH_BLOCK(0), block_start = strstart;
  730.  
  731.         } else if (match_available) {
  732.             /* If there was no match at the previous position, output a
  733.              * single literal. If there was a match but the current match
  734.              * is longer, truncate the previous match to a single literal.
  735.              */
  736.             Tracevv((stderr,"%c",window[strstart-1]));
  737.             if (ct_tally (0, window[strstart-1])) {
  738.                 FLUSH_BLOCK(0), block_start = strstart;
  739.             }
  740.             strstart++;
  741.             lookahead--;
  742.         } else {
  743.             /* There is no previous match to compare with, wait for
  744.              * the next step to decide.
  745.              */
  746.             match_available = 1;
  747.             strstart++;
  748.             lookahead--;
  749.         }
  750.         Assert (strstart <= isize && lookahead <= isize, "a bit too far");
  751.  
  752.         /* Make sure that we always have enough lookahead, except
  753.          * at the end of the input file. We need MAX_MATCH bytes
  754.          * for the next match, plus MIN_MATCH bytes to insert the
  755.          * string following the next match.
  756.          */
  757.         while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  758.     }
  759.     if (match_available) ct_tally (0, window[strstart-1]);
  760.  
  761.     return FLUSH_BLOCK(1); /* eof */
  762. }
  763.